

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:

    //从链表中删去总和值为零的连续节点
    ListNode* removeZeroSumSublists(ListNode* head) {
        ListNode* prv = new ListNode(0, head);
        
        ListNode* i = prv;
        while (i != nullptr)
        {
            int sum = 0;
            ListNode* j = i->next;
            while (j != nullptr)
            {
                sum += j->val;
                if (sum == 0)
                {
                    //删除节点
                    ListNode* del = i->next;
                    i->next = j->next;
                    while (del != j->next)
                    {
                        ListNode* next = del->next;
                        delete del;
                        del = next;
                    }

                }
                j = j->next;
            }
            i = i->next;
        }

        ListNode* ret = prv->next;
        delete prv;
        return ret;
    }


    //链表内指定区间反转
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* del = new ListNode(-1);
        del->next = head;

        ListNode* guard = del;
        //找起始头
        for (int i = 1; i<m; ++i)
        {
            guard = guard->next;
        }

        //翻转
        ListNode* cur = guard->next;
        ListNode* prv = guard;

        for (int i = m; i<=n; ++i)
        {
            ListNode* next = cur->next;
            cur->next = prv;
            prv = cur;
            cur = next;
        }
        guard->next->next = cur;
        guard->next = prv;

        ListNode* ret = del->next;
        delete del;
        return ret;
    }
};